Page({
  data: {
    title: "",
    typeOptions: ["论文", "专利", "获奖", "项目"],
    typeValues: ["paper", "patent", "award", "project"], // 对应的英文值
    typeIndex: 0,
    levelOptions: ["校级", "市级", "省级", "国家级"],
    levelValues: ["school", "municipal", "provincial", "national"], // 对应的英文值
    levelIndex: 0,
    role: "",
    description: "",
    files: [],
    submitting: false,
  },

  onTitle(e) {
    this.setData({ title: e.detail.value });
  },
  onTypeChange(e) {
    this.setData({ typeIndex: parseInt(e.detail.value) });
  },
  onLevelChange(e) {
    this.setData({ levelIndex: parseInt(e.detail.value) });
  },
  onRole(e) {
    this.setData({ role: e.detail.value });
  },
  onDesc(e) {
    this.setData({ description: e.detail.value });
  },

  // 选择文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 9,
      type: "file",
      success: (res) => {
        const tempFiles = res.tempFiles;
        const files = this.data.files;

        tempFiles.forEach((file) => {
          files.push({
            name: file.name,
            path: file.path,
            size: file.size,
            type: file.type || "unknown",
          });
        });

        this.setData({ files });
        wx.showToast({
          title: `已选择${tempFiles.length}个文件`,
          icon: "success",
        });
      },
      fail: (error) => {
        console.error("选择文件失败:", error);
        wx.showToast({
          title: "选择文件失败",
          icon: "error",
        });
      },
    });
  },

  // 预览文件
  previewFile(e) {
    const index = e.currentTarget.dataset.index;
    const file = this.data.files[index];

    if (!file) return;

    // 判断文件类型
    const fileExtension = file.name.split(".").pop().toLowerCase();
    const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "webp"];

    if (imageExtensions.includes(fileExtension)) {
      // 图片文件，使用预览图片
      wx.previewImage({
        urls: [file.path],
        current: file.path,
      });
    } else {
      // 其他文件类型，显示提示
      wx.showModal({
        title: "文件预览",
        content: `文件：${file.name}\n大小：${(file.size / 1024).toFixed(
          2
        )}KB\n\n该文件类型暂不支持预览`,
        showCancel: false,
      });
    }
  },

  // 删除文件
  removeFile(e) {
    const index = e.currentTarget.dataset.index;
    const files = this.data.files;

    wx.showModal({
      title: "确认删除",
      content: "确定要删除这个文件吗？",
      success: (res) => {
        if (res.confirm) {
          files.splice(index, 1);
          this.setData({ files });
          wx.showToast({
            title: "已删除",
            icon: "success",
          });
        }
      },
    });
  },

  async submit() {
    if (this.data.submitting) return;
    const {
      title,
      typeValues,
      typeIndex,
      levelValues,
      levelIndex,
      role,
      description,
      files,
    } = this.data;

    if (!title.trim()) {
      wx.showToast({ title: "请输入标题", icon: "none" });
      return;
    }

    if (!role.trim()) {
      wx.showToast({ title: "请输入个人角色", icon: "none" });
      return;
    }

    this.setData({ submitting: true });

    try {
      const local = require("../../../../utils/local");

      // 处理文件数据
      const processedFiles = files.map((file) => ({
        name: file.name,
        url: file.path, // 在实际应用中，这里应该是上传后的URL
        size: file.size,
        type: file.type,
      }));

      const res = local.addResearch({
        title: title.trim(),
        type: typeValues[typeIndex], // 使用英文值
        level: levelValues[levelIndex], // 使用英文值
        role: role.trim(),
        description: description.trim(),
        files: processedFiles,
        date: new Date().toLocaleDateString(),
      });

      if (res.success) {
        wx.showToast({ title: "添加成功", icon: "success" });
        setTimeout(() => {
          wx.navigateBack();
        }, 500);
      } else {
        wx.showToast({ title: res.message || "添加失败", icon: "error" });
      }
    } catch (error) {
      console.error("提交失败:", error);
      wx.showToast({
        title: "提交失败，请重试",
        icon: "error",
      });
    } finally {
      this.setData({ submitting: false });
    }
  },
});
